﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebSimplicity.Data;
using WebSimplicity.Admin.Models;
using System.Web.Security;
using WebSimplicity.Data.Helpers;
using System.Web.Profile;

namespace WebSimplicity.Admin.Controllers
{
    public class InstallController : Controller
    {
        //
        // GET: /Install/

        public ActionResult Index()
        {
            if (Config.GetApplicationSetting("Installed") == "true")
            {
                return RedirectToAction("Setup");
            }
            return View();
        }
        [HttpPost]
        public ActionResult Install(Installer install)
        {
            Config.BuildConnectionString(
                install.Server,
                install.Database,
                install.Username,
                install.Password);
            Database.Install();
            if (install.InstallBlogs)
            {
                Blogs.install();
            }
            if (install.InstallForums)
            {
                Forums.install();
            }
            if (install.InstallStores)
            {
                Stores.install();
            }
            Config.AddApplicationSetting("Installed", "true");
            Config.AddApplicationSetting("InstallType", install.InstallType.ToString());
            return RedirectToAction("Setup");
        }

        public ActionResult Setup()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Setup(WebsiteSetup setup)
        {
            Application app = new Application();
            app.Create();
            app.Activate();
            PasswordGenerator pw = new PasswordGenerator();
            pw.Minimum = 7;
            MembershipUser user = Membership.CreateUser(setup.Email, pw.Generate(), setup.Email);
            FormsAuthentication.SetAuthCookie(user.UserName, false);
            Account acct = new Account();
            acct.AccountId = new Guid();
            acct.AccountName = "Simplicity Digital";
            acct.PrimaryUser = (Guid)user.ProviderUserKey;
            acct.Create();
            ProfileBase profile = ProfileBase.Create(user.UserName);
            profile["AccountId"] = acct.AccountId;
            profile.Save();
            setup.website.ApplicationId = app.ApplicationId;
            Website website = setup.website.Create();
            Domain domain = new Domain();
            domain.DomainName = setup.domain.DomainName;
            domain.WebsiteId = website.WebsiteId;
            domain.ForceWWW = setup.domain.ForceWWW;
            domain.Create();
            Config.AddApplicationSetting("BaseDomainName", domain.DomainName);
            return RedirectToAction("index", "home");
        }
    }
}
